import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/extension/index.dart';

import '../../../../common/api/x_message_assemble_communicate.dart';
import '../../../../common/models/im/im_message.dart';
import '../../../../common/style/color.dart';
import '../../../../common/utils/log_util.dart';
import '../../../../common/widgets/o2_stateless_widget.dart';
import '../im_chat/widgets/msg_body.dart';
import 'index.dart';

class ImChatMessageListPage extends GetView<ImChatMessageListController> {
  @override
  final String? tag;

  const ImChatMessageListPage({Key? key, required this.tag}) : super(key: key);

   static void open(List<String> messageIdList, String msgId) {
    Get.lazyPut<ImChatMessageListController>(
        () => ImChatMessageListController(),
        tag: msgId);
    // Get.to(() => ImChatMessageListPage(tag: msgId),
    //     arguments: {'messageIdList': messageIdList}, preventDuplicates: false);
    final args = ImChatMessageListPageArgs(messageIdList);
    pushMessageListPage(ImChatMessageListPage(tag: msgId), msgId, args);
  }

  static Future<void> pushMessageListPage(ImChatMessageListPage messageListPage, String tag, ImChatMessageListPageArgs args) async {
    final context = Get.context;
    if (context == null) {
      OLogger.d('pushMessageListPage context is null');
      return ;
    }
    await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => messageListPage, settings: RouteSettings(name: tag, arguments: args)),
    );
  }

  @override
  Widget build(BuildContext context) {
     ImChatMessageListPageArgs? map;
    if (ModalRoute.of(context)?.settings.arguments is ImChatMessageListPageArgs) {
      map = ModalRoute.of(context)?.settings.arguments as ImChatMessageListPageArgs;
      OLogger.d('message List    build args: ${map.toJson()}');
    }
    return GetBuilder<ImChatMessageListController>(
      tag: tag,
      builder: (_) {
         if (map != null) {
            controller.initFromNavigatorArgs(map.toJson());
        }
        return Scaffold(
          appBar: AppBar(title: Text("im_chat_msg_forward_tag".tr)),
          body: SafeArea(
            child: Container(
                color: Theme.of(context).scaffoldBackgroundColor,
                child: Padding(
                    padding: const EdgeInsets.only(top: 10),
                    child: Obx(
                      () => controller.state.msgList.length < 1
                          ? O2UI.noResultView(context)
                          : ListView.separated(
                              itemBuilder: (context, index) {
                                final msg = controller.state.msgList[index];
                                return _msgItemView(context, msg);
                              },
                              separatorBuilder: (context, index) {
                                return const Divider(
                                  height: 1,
                                );
                              },
                              itemCount: controller.state.msgList.length),
                    ))),
          ),
        );
      },
    );
  }

  Widget _msgItemView(BuildContext context, IMMessage msg) {
    return InkWell(
        onTap: () => controller.clickMsgItem(msg),
        child: Padding(
            padding: const EdgeInsets.all(10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(
                  width: 50,
                  height: 50,
                  child: O2UI.personAvatar(msg.createPerson!, 25),
                ),
                const SizedBox(width: 10),
                Expanded(flex: 1, child: _msgContentView(context, msg))
              ],
            )));
  }

  Widget _msgContentView(BuildContext context, IMMessage msg) {
    final time = DateTime.tryParse(msg.createTime ?? "");

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(msg.createPerson?.o2NameCut() ?? '',
                style: Theme.of(context).textTheme.bodyLarge),
            const Spacer(),
            Text(time?.chatMsgShowTimeFormat() ?? '',
                style: Theme.of(context).textTheme.bodySmall)
          ],
        ),
        const SizedBox(height: 10),
        _cardMsgBody(msg),
        if (msg.quoteMessage != null) _quoteMsgView(context, msg.quoteMessage!, false),
      ],
    );
  }

  Widget _cardMsgBody(IMMessage msg) {
    final msgBody =
        MsgBodyWidget(msgBody: msg.toBody()!, isSender: false, msgId: msg.id!, systemTextColor: true);
    if (msg.toBody()?.type == 'file' ||
        msg.toBody()?.type == 'audio' ||
        msg.toBody()?.type == 'location' ||
        msg.toBody()?.type == 'process' ||
        msg.toBody()?.type == 'messageHistory') {
      return Padding(
          padding: const EdgeInsets.only(right: 20),
          child: Container(
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: AppColor.imReceiverColor,
              borderRadius: BorderRadius.circular(4),
            ),
            child: msgBody,
          ));
    }
    return msgBody;
  }

   Widget _quoteMsgView(
      BuildContext context, IMMessage quoteMessage, bool isRight) {
    String text =
        '${quoteMessage.createPerson?.o2NameCut()}: ${quoteMessage.toBody()?.conversationBodyString()}';
    if (quoteMessage.toBody()?.type == 'image') {
      text = '${quoteMessage.createPerson?.o2NameCut()}: ';
    } else if (quoteMessage.toBody()?.type == 'location') {
      text += ' ${quoteMessage.toBody()?.address}';
    } else if (quoteMessage.toBody()?.type == 'file') {
      text += ' ${quoteMessage.toBody()?.fileName}';
    } else if (quoteMessage.toBody()?.type == 'audio') {
      text += ' ${quoteMessage.toBody()?.audioDuration ?? 0} "';
    }
    return Padding(
        padding: const EdgeInsets.only(top: 2),
        child: GestureDetector(
            onTap: () {
              controller.clickMsgItem(quoteMessage);
            },
            child: Container(
              decoration: BoxDecoration(
                color: AppColor.imQuoteMsgColor,
                borderRadius: BorderRadius.circular(4),
              ),
              padding: const EdgeInsets.all(5),
             
              child: Row(
                  mainAxisAlignment:
                      isRight ? MainAxisAlignment.end : MainAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container( 
                      constraints: const BoxConstraints(maxWidth: 200), 
                      child: Text(text, style: Theme.of(context).textTheme.bodySmall, maxLines: 3, overflow: TextOverflow.ellipsis)),
                    if (quoteMessage.toBody()?.type == 'image') _quoteMsgPictureBody(quoteMessage)
                  ]),
            )));
  }

  Widget _quoteMsgPictureBody(IMMessage quoteMessage) {
    var imageUrl = MessageCommunicationService.to
        .getIMMsgImageUrl(quoteMessage.toBody()!.fileId!);
    return Padding(
        padding: const EdgeInsets.only(left: 5),
        child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Image.network(imageUrl,
                headers: controller.headers, width: 48, height: 48)));
  }
}
